using System;
using System.Collections.Generic;
using Microsoft.Xna.Framework.Content.Pipeline.Serialization.Compiler;
using Microsoft.Xna.Framework.Content.Pipeline.Graphics;
using Scurvy.Media.Pipeline.Video.Avi;
using Scurvy.Media.VideoModel;
using Microsoft.Xna.Framework.Graphics;

namespace Scurvy.Media.Pipeline.Video
{

    public abstract class VidContentWriter<T> : ContentTypeWriter<T> where T : IVideoContent
    {
        protected override void Write(ContentWriter output, T value)
        {
            GC.Collect();

            bool metaDataWritten = false;

            using (value)
            {
                foreach (Texture2DContent tex in value.Frames)
                {
                    if (!metaDataWritten)
                    {
                        /*
                        This is in the foreach simply because of the
                        AviVideoContent implementation, which doesn't know
                        The size of a given frame until the first one is read.
                        And since now we don't read anything into memory until
                        this loop, this is the semi-hack that had to go in :-)
                         */
                        output.Write(value.FrameCount);
                        output.Write(value.FrameRate);
                        output.Write(value.Size);
                        output.Write((short)value.PlayType);
                        output.Write(value.UseCompression);
                        metaDataWritten = true;
                    }

                    byte[] pix = tex.Faces[0][0].GetPixelData();

                    PlatformSurface surface = PlatformSurface.Create();
                    surface.WriteToXnb(output, pix);
                    //WriteData(output, pix);

                }
            }
        }


        /// <summary>
        /// Writes the texture data to the stream without modification.
        /// </summary>
        private static void WriteData(ContentWriter output, byte[] pix)
        {
            output.Write(pix.Length);
            output.Write(pix);
        }

        public override string GetRuntimeReader(Microsoft.Xna.Framework.TargetPlatform targetPlatform)
        {
            return typeof(VidReader).AssemblyQualifiedName;
        }
    }
}
